package com.xai.pg.util;

import java.io.StringWriter;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

/**
 * @Author xxx
 * @Date 2018-12-24 16:29:42
 * @Desc VMUtil
 */
public class VMUtil {

    private static VelocityEngine velocityEngine = new VelocityEngine();

    static {
        velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
        velocityEngine.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        velocityEngine.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        velocityEngine.init();
    }

    public static boolean jpa = false;
    public static boolean isRestful = false;
    public static boolean receiveBody = false;

    public static String toStr(Object obj, String vmPath) {
        Template t = velocityEngine.getTemplate(vmPath);
        VelocityContext ctx = new VelocityContext();
        ctx.put("data", obj);
        ctx.put("jpa", jpa);
        ctx.put("restful", isRestful);
        ctx.put("receiveBody", receiveBody);
        StringWriter sw = new StringWriter();
        t.merge(ctx, sw);
        return sw.toString();
    }
}
